跳到主要内容

14 最长公共前缀

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnmav1/

https://leetcode.cn/problems/longest-common-prefix/description/

cost: 13m22s

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string_view r = strs[0];
for (int i = 1; i < strs.size(); i++) {
const string& str = strs[i];
if (str.length() == 0) {
r = "";
break;
}
for (int j = 0; j <= str.size() && j <= r.size(); j++) {
if (j == str.size() || j == r.size()) {
r = r.substr(0, j);
break;
}
if (str[j] != r[j]) {
r = r.substr(0, j);
break;
}
}
}
string rr(r);
return rr;
}
};
  • 时间复杂度:O(mn), m 是字符串数组中的字符串的平均长度,n 是字符串的数量
  • 空间复杂度:O(n1)